﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace LogoScriptIDE
{
    /// <summary>
    /// 配置文件
    /// </summary>
    class Config
    {
        private Dictionary<string, string> dict
            = new Dictionary<string, string>();

        /// <summary>
        /// 保存配置文件
        /// </summary>
        /// <param name="tw">输出器</param>
        public void Save(TextWriter tw)
        {
            foreach (var pair in dict)
                tw.WriteLine(pair.Key + " = " + pair.Value);
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="tr">读取器</param>
        public void Load(TextReader tr)
        {
            dict.Clear();
            while (true)
            {
                string s = tr.ReadLine();
                if (s == null) break;

                // 以第一个等号将每行配置分为两部分
                // 左边为键，右边为值
                int i = s.IndexOf('=');
                if (i == -1) continue;

                string name = s.Substring(0, i).Trim();
                string data = s.Substring(i + 1).Trim();
                dict.Add(name, data);
            }
        }

        /// <summary>
        /// 设置配置文件
        /// </summary>
        /// <param name="name">键</param>
        /// <param name="data">值</param>
        public void SetField(string name, string data)
        {
            if (dict.ContainsKey(name))
                dict[name] = data;
            else
                dict.Add(name, data);
        }

        /// <summary>
        /// 获取配置信息
        /// </summary>
        /// <param name="name">键</param>
        /// <returns>对应的值，若键不存在则返回空字符串</returns>
        public string GetField(string name)
        {
            if (dict.ContainsKey(name))
                return dict[name];
            else
                return "";
        }

        /// <summary>
        /// 尝试读取double类型的值
        /// </summary>
        /// <param name="name">键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>转换成double类型的键所对应的值，若转换失败则返回默认值</returns>
        public double TryGetDouble(string name, double defaultValue)
        {
            try
            {
                string data = GetField(name);
                double answer = Double.Parse(data);
                return answer;
            }
            catch
            {
                return defaultValue;
            }
        }
    }
}
